package com.uvlab.sitespot.service.sedt;


import com.uvlab.sitespot.common.JxNode;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/4/20.
 * modified by yanglu on 2016/4/27  update the methods
 * modified by yl on 2016/5/9  update method add
 * modifiled by jys 2016-7-19 using hashmap and client shouldn't know root dir
 */
public class JxSiteEditorService {

    protected String rootdir;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public JxSiteEditorService() {

    }

    public void init(String rootdir) {
        if (rootdir.equals(""))
            this.rootdir = "E:\\aaa\\";
        else
//          this.rootdir = rootdir;
            this.rootdir="E:\\aaa\\";
    }

    public  String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public LinkedHashMap<String,JxNode> find() {
       return  findinside(this.rootdir);
    }

    //找到路径为id的节点，返回id路径下所有的文件或文件夹
    public  LinkedHashMap<String,JxNode> find(String id) {
        String curdir=this.rootdir+id;
        return findinside(curdir);
    }

    //将当前path路径下的文件或文件夹以list列表形式返回，list中存储Node对象
    //XXXXXX----id-----XXXXXX
    protected LinkedHashMap<String,JxNode> findinside(String path) {
        LinkedHashMap<String,JxNode> ret=new LinkedHashMap<>();
        File cur = new File(path);
        String id,suffix, shortname, dataTimeStr,content,parent,name;
        boolean categories;
        int state;
        Date lastModified;
        List<String> children;
        if(isDir(cur)) {
            File[] files = cur.listFiles();
//          System.out.println(files.toString());
            for (File f : files) {
                shortname = f.getName();
                //文件最后修改时间
                lastModified = new Date(f.lastModified());
                //把它转化为yyyy-MM-dd HH:mm:ss形式
                dataTimeStr = formatter.format(lastModified);
                suffix = shortname.substring(shortname.lastIndexOf(".") + 1);
                if (f.isDirectory()) {
                    suffix = "";
                    categories =true;
                    children = chil(f);
                    content = null;
                    name= shortname;
                } else {
                    categories = false;
                    children = null;
                    content = getContent(f.getPath());
                    name = shortname.substring(0,shortname.lastIndexOf(".") - 1);
                    //显示文件信息
                    //content=getContent(path);
                }
                String idx=f.getPath();
                id = f.getPath().replace(this.rootdir,"");
                parent = f.getParent();
                state=JxNode.NORMAL;
                JxNode node=new JxNode(id, id, shortname, categories, content, parent, children, dataTimeStr, suffix, name, state);
                ret.put(id,node);
            }
        }else if(!isDir(cur)){
            return null;
        }
        return ret;
    }

    /**
     * Return the detail of the specified node.
     *
     * @param id
     * @return
     */
    public JxNode get(String id) {

        String curdir=this.rootdir+id;
        String suffix, shortname, dataTimeStr,content,parent,name;
        boolean categories;
        int state;
        Date lastModified;
        List<String> children;
        File cur= new File(curdir);
        shortname=cur.getName();
        parent=cur.getParent();
        suffix = shortname.substring(shortname.lastIndexOf(".") + 1);
        //文件最后修改时间
        lastModified = new Date(cur.lastModified());
        //把它转化为yyyy-MM-dd HH:mm:ss形式
        dataTimeStr = formatter.format(lastModified);
        if(isDir(cur)){
            suffix = "";
            categories =true;
            children = chil(cur);
            content = null;
            name= shortname;

        }else{
            categories = false;
            children = null;
            content = getContent(cur.getPath());
            name = shortname.substring(0, shortname.lastIndexOf(".") - 1);
        }
        dataTimeStr = formatter.format(lastModified);
        state=JxNode.NORMAL;

        JxNode node=new JxNode(id, id, shortname,categories, content, parent, children, dataTimeStr, suffix, name,state);
        return node;
    }

    //获取子节点相对路径列表 2016/04/27
    public List<String> chil(File f){
        List<String> list=new ArrayList<String>();
        File[] files = f.listFiles();
        for(File file : files){
            try {
                list.add(file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * Update the node.
     *
     * @param id
     * @param node
     * @return
     */
    public JxNode set(String id, JxNode node) {
        // TODO
        //done
        String curdir=rootdir+id;
        File file=new File(curdir);
        node.setState(JxNode.EDITTING);
        FileWriter fw= null;
        try {
            fw = new FileWriter(curdir);
            fw.write(node.getContent());
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Date lastModified = new Date(file.lastModified());
        String dataTimeStr = formatter.format(lastModified);
        node.setDataTimeStr(dataTimeStr);
        node.setState((JxNode.NORMAL));
        return node;
    }

    /**
     * Save the data in the node parameter as a new file.
     *
     *
     * @return The JxNode object.
     */
    public JxNode add(JxNode node){
        String path=this.rootdir+node.getId();
        File cur= new File(path);
        String suffix, shortname, dataTimeStr,content,parent,name;
        boolean categories;
        int state;
        Date lastModified;
        List<String> children;
        if(isDir(cur)){
            categories=true;
            if(cur.exists()){
                System.out.println("the folder has exists");
                return null;
            }else{
                cur.mkdir();
            }
            children=chil(cur);
        }
        else{
            categories=false;
            if(cur.exists()){
                System.out.println("the folder has exists");
                return null;
            }
            else {
                try {
                    cur.createNewFile();
                    FileWriter fw = new FileWriter(path);
                    fw.write(node.getContent());
                    fw.flush();
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        shortname=cur.getName();
        parent=cur.getParent();
        suffix = shortname.substring(shortname.lastIndexOf(".") + 1);
        //文件最后修改时间
        lastModified = new Date(cur.lastModified());
        //把它转化为yyyy-MM-dd HH:mm:ss形式
        dataTimeStr = formatter.format(lastModified);
        if(isDir(cur)){
            suffix = "";
            categories =true;
            children = chil(cur);
            content = null;
            name= shortname;

        }else{
            categories = false;
            children = null;
            content =node.getContent();
            name = shortname.substring(0, shortname.lastIndexOf(".") - 1);
        }
        dataTimeStr = formatter.format(lastModified);
        state=JxNode.NORMAL;

        JxNode ret=new JxNode(node.getId(), node.getId(), shortname,categories, content, parent, children, dataTimeStr, suffix, name,state);
        return ret;
    }

    /**
     * Delete a node file from the file system. 2016/04/27
     *
     * @param id
     * @return
     */
    public boolean remove(String id) {
        String curdir=this.rootdir+id;
        File cur=new File(curdir);
        if(cur.exists()) {
            deleteFile(cur);
            return true;
        }else
            return false;
    }
    private void deleteFile(File file){
            if(file.isFile()){
                file.delete();
            }
            else if(file.isDirectory()){
                File files[] = file.listFiles();
                for(int i=0;i<files.length;i++){
                    this.deleteFile(files[i]);
                }
                file.delete();
            }
        }

    /**
     * 获得详细内容 2016/04/27
     */
    public String getContent(String path){
//        InputStream inputStream=null;
        String content=null;
//        try {
//            inputStream=new FileInputStream(path);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        int counte=0;
//        byte[] b=new byte[1024];
//    try {
//        while((counte=inputStream.read(b))!=-1){
//            if(b.length==counte) {
//                byte[] b1=new byte[b.length*3/2+1];
//                for(int i=0;i<b.length;i++)
//                    b1[i]=b[i];
//                b=b1;
//            }
//            content=new String(b);
//        }
//        inputStream.close();
//    } catch (IOException e) {
//        e.printStackTrace();
//    }
        InputStream is = null;
        try {
            is = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line; // 用来保存每行读取的内容
        StringBuffer buffer=new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try {
            line = reader.readLine(); // 读取第一行
            while (line != null) { // 如果 line 为空说明读完了
                buffer.append(line); // 将读到的内容添加到 buffer 中
                buffer.append("\n"); // 添加换行符
                line = reader.readLine(); // 读取下一行
            }
            reader.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        content=buffer.toString();
        return content;
}
    /**
     * 判断文件类型 2016/04/27
     */
    public boolean isDir(File file){
        if(file.isDirectory()){
            return true;
        }else
            return false;
    }
}



